package com.lyx.bank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.lyx.bank.entity.Account;
import com.lyx.bank.entity.TransactionRecord;
import com.lyx.bank.feign.RecordsFeign;
import com.lyx.bank.handler.BusinessException;
import com.lyx.bank.response.Result;
import com.lyx.bank.response.ResultCode;
import com.lyx.bank.service.AccountService;
import com.lyx.bank.service.RecordsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName AccountController
 * @Description: TODO
 * @Author 86152
 * @Date 2022/4/22
 * @Version V1.0
 **/
@Api(tags = "角色模块")
@RestController
public class AccountController {

    @Autowired
    AccountService accountService;

    @ApiOperation(value = "查询用户列表")
    @GetMapping("/getAll")
    public Result GetAll() {
        List<Account> list = accountService.list();
        return Result.ok().data("list", list);
    }

    @ApiOperation(value = "登录是否成功")
    @GetMapping("/login")
    public Result login(
            @RequestParam(value = "cardNo", required = true) String cardNo,
            @RequestParam(value = "password", required = true) String password
    ) {
        Account user = accountService.login(cardNo);
        //判断账号是存在
        if (user != null) {
            String userPwd = user.getPassword();
            //判断密码是否正确
            if (password != null && password.equals(userPwd)) {
                return Result.ok().data("user", user.getCardNo());
            } else {
                return Result.error(ResultCode.USER_CREDENTIALS_ERROR);
            }
        } else {
            return Result.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
    }

    /**
     * 查询余额
     *
     * @param cardNo
     * @return 余额
     */
    @ApiOperation(value = "查询余额")
    @GetMapping("/find")
    public Result find(@RequestParam(value = "cardNo") String cardNo) {

        QueryWrapper<Account> qw = new QueryWrapper<>();
        qw.eq("cardNo", cardNo);
        Account account = accountService.getBaseMapper().selectOne(qw);
        return Result.ok().data("balance", account.getBalance());


    }

    @ApiOperation(value = "修改密码")
    @PutMapping("/update")
    public Result update(@RequestParam(value = "cardNo") String cardNo,
                         @RequestParam(value = "password", required = true) String pass,
                         @RequestParam(value = "checkPass", required = true) String checkPass) {

        if (!pass.equals(checkPass)) {
            throw new BusinessException(ResultCode.USER_NOT_LIKE.getCode(),
                    ResultCode.USER_NOT_LIKE.getMessage());
        }
        if (cardNo == null || cardNo.equals("")) {
            throw new BusinessException(ResultCode.USER_NOT_LOGIN.getCode(),
                    ResultCode.USER_NOT_LOGIN.getMessage());
        }
        int i = accountService.updatePass(cardNo, pass);
        if (i == 0) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());

        }

        return Result.ok().data("update", i);
    }


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    RecordsService recordsService;

    /**
     *
     * @param cardNo 收款人卡号
     * @param cardNoI 付款人卡号
     * @param tranMoney 交易金额
     * @return
     */

    @ApiOperation(value = "转账")
    @PutMapping("/transferAccounts")
    public Result transferAccounts(
    @RequestParam(value = "cardNo") String cardNo,
    @RequestParam(value = "cardNoI") String cardNoI,
    @RequestParam(value = "tranMoney") Double tranMoney
    ){


        //执行转账
        int transaction = accountService.transaction(cardNo, tranMoney);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        Date data = java.sql.Date.valueOf(format);

        //订单信息 收款人的订单类型
        String type = "收到";
        //查询 收款人余额
        QueryWrapper<Account> qw = new QueryWrapper<>();
        qw.eq("cardNo", cardNo).select("balance");
        Account balance = accountService.getOne(qw);
        // 收款人备注
        String remark =cardNo +"收到了"+cardNoI+"的" +tranMoney+"元" ;



        //将收款人的订单信息消息给mq接受
        Map<String,Object> map = new HashMap<>();
        map.put("cardNo",cardNo);
        map.put("amout",tranMoney);
        map.put("balance",balance.getBalance());
        map.put("transactionDate",data);
        map.put("transactionType",type);
        map.put("remark",remark);
        rabbitTemplate.convertAndSend("bank.fanout","",map);

        //如果转账成功给自己账户扣款 并且生成订单
        if (transaction>0){

            int transfer = accountService.transfer(cardNoI, tranMoney);

            //订单信息 付款人的订单类型
            String type2 = "支出";
            //付款人的余额
            QueryWrapper<Account> qw2 = new QueryWrapper<>();
            qw2.eq("cardNo", cardNoI).select("balance");
            Account balance2 = accountService.getOne(qw2);
            // 收款人备注
            String remark2 =cardNoI +"付款给"+cardNo+"了" +tranMoney+"元" ;

            Map<String,Object> map2 = new HashMap<>();
            map2.put("cardNo",cardNoI);
            map2.put("amout",tranMoney);
            map2.put("balance",balance2.getBalance());
            map2.put("transactionDate",data);
            map2.put("transactionType",type2);
            map2.put("remark",remark2);
            rabbitTemplate.convertAndSend("bank.fanout","",map2);
            if (transfer>0) {
                // recordsService.createdRecords2(map);
                // //收款人生成订单
                // recordsService.createdRecords(map);
                // //付款人生成订单
                // recordsService.createdRecords(map2);
            }

                return Result.ok();
        }
        return Result.ok();
    }


}
